#!/usr/bin/python3

import urllib
import uapool
import re
import json
import zjl_util


def get_video_infos(index_url):
    uapool.UA()
    doc = zjl_util.get_doc(index_url)
    pat_list = 'class=\'content-list\'>(.*?)</div>'
    pat_href = 'target="_blank" href=\'(.*?)\' title=\'(.*?)\''
    title_href = re.compile(pat_href, re.S).findall(doc)
    return title_href


def get_video_down_url(video_url):
    uapool.UA()
    r_index = str(video_url).rindex('/')
    video_id = str(video_url[r_index + 1:]).replace('.html', '')
    # print(video_id)
    get_info_url = 'https://liveapi.huya.com/moment/getMomentContent?videoId=' + video_id
    doc = zjl_util.get_doc(get_info_url)
    j = json.loads(doc)
    order_config = {'流畅': 1, '超清': 3, '原画': 2}  # 下载优先级，优先原画
    definitions = j['data']['moment']['videoInfo']['definitions']
    v_info = {'defName': '', 'url': ''}
    # print(definitions)
    for i in definitions:
        item_level = order_config[i['defName']]

        if not v_info['defName'] in order_config:
            v_info['defName'] = i['defName']
            v_info['url'] = i['url']
            continue

        current_level = order_config[v_info['defName']]
        if current_level is None or current_level < item_level:
            v_info['defName'] = i['defName']
            v_info['url'] = i['url']
    return v_info['url']


def main():
    index_url = 'https://v.huya.com/u/231498536/video.html?sort=news&p=2'
    title_href_s = get_video_infos(index_url)

    video_info_s = []
    for i in title_href_s:
        uri = i[0]
        video_url = ''
        if str(uri).startswith('/'):
            video_url = uapool.get_base_url(index_url) + uri
        elif str(uri).startswith('http'):
            video_url = uri
        else:
            r_index = index_url.rindex('/')
            video_url = index_url[0: r_index + 1] + uri

        '''  video_url = 'https://v.huya.com/play/276702244.html' '''
        down_url = get_video_down_url(video_url)
        video_info = {'title': i[1], 'url': down_url}
        video_info_s.append(video_info)

    print(video_info_s)
    for i in video_info_s:
        print('wget ' + i['url'] + ' -O \'' + i['title'] + '.mp4\'')
        print('sleep 240')


if __name__ == "__main__":
    main()
